package cn.ug.msg.service.impl;

import cn.ug.bean.base.SerializeObject;
import cn.ug.core.ensure.Ensure;
import cn.ug.enums.ThirdSourceEnum;
import cn.ug.feign.MemberThirdService;
import cn.ug.member.bean.response.MemberThirdFindBean;
import cn.ug.msg.bean.SmsBean;
import cn.ug.msg.bean.status.CommonConstants;
import cn.ug.msg.mapper.MemberInfoMapper;
import cn.ug.msg.mapper.TemplateMapper;
import cn.ug.msg.mapper.entity.MemberInfo;
import cn.ug.msg.mapper.entity.Template;
import cn.ug.msg.mq.Msg;
import cn.ug.msg.service.MsgService;
import cn.ug.msg.service.SmsService;
import cn.ug.msg.web.utils.HttpClientUtil;
import cn.ug.util.AppPushUtils;
import cn.ug.util.UF;
import com.gexin.rp.sdk.base.IPushResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ug.util.ConstantUtil.COMMA;

@Service
public class MsgServiceImpl implements MsgService {
    //todo 短信签名
    @Value("${sms.sign}")
    private  String SMS_SIGN_NAME ;
    @Resource
    private SmsService smsService;
    @Resource
    private TemplateMapper templateMapper;
    @Resource
    private MemberInfoMapper memberInfoMapper;
    private Log log = LogFactory.getLog(MsgServiceImpl.class);
    @Autowired
    private MemberThirdService memberThirdService;
    @Value("${push.skip.type}")
    private String skipType;
    @Value("${push.skip.h5.url}")
    private String h5Url;
    @Value("${zhuanxinyun.sms.url}")
    private String url;
    @Value("${zhuanxinyun.sms.appKey}")
    private String appKey;
    @Value("${zhuanxinyun.sms.appSecret}")
    private String appSecret;

    /**
     * 安卓
     */
    // 由IGetui管理页面生成，是您的应用与SDK通信的标识之一，每个应用都对应一个唯一的AppID
    private static String APPID_ANDROID = "jmy8iaPpAC9m7A1rVT5hY2";
    // 预先分配的第三方应用对应的Key，是您的应用与SDK通信的标识之一。
    private static String APPKEY_ANDROID = "buOLV8Oj228hHu0ApftEM6";
    // 个推服务端API鉴权码，用于验证调用方合法性。在调用个推服务端API时需要提供。（请妥善保管，避免通道被盗用）
    private static String MASTERSECRET_ANDROID = "pPILaZuC2i8NO2eWhJp529";


    /**
     * 个推-ios
     */
    //todo
    private static String APPID_IOS = "";
    // 预先分配的第三方应用对应的Key，是您的应用与SDK通信的标识之一。
    private static String APPKEY_IOS = "";
    // 个推服务端API鉴权码，用于验证调用方合法性。在调用个推服务端API时需要提供。（请妥善保管，避免通道被盗用）
    private static String MASTERSECRET_IOS = "";

    @Override
    public void sendMsg(Msg msg) {
        //获取模版
        Template template = templateMapper.findByType(msg.getType());
        Ensure.that(template == null).isTrue("19000404");

        //定义短信通知类
        SmsBean smsBean = new SmsBean();

        //业务处理
        //发送短信
        String content = getContent(msg.getParamMap(), template.getContent());
        if (StringUtils.isNotBlank(msg.getNoticeType())) {
            String[] types = StringUtils.split(msg.getNoticeType(), COMMA);
            if (types != null && types.length > 0) {
                //1:短信；2：站内信；3：推送，个多用","分割
                for (String type : types) {
                    if (StringUtils.equals(type, String.valueOf(1))) {
                        sendSms(template.getFilingNumber(), msg.getMobile(), content, msg.getParamMap());
                    }
                    if (StringUtils.equals(type, String.valueOf(2))) {
                        MemberInfo memberInfo = new MemberInfo();
                        memberInfo.setId(UF.getRandomUUID());
                        memberInfo.setMemberId(msg.getMemberId());
                        memberInfo.setTitle(template.getTitle());
                        memberInfo.setContent(content);
                        memberInfo.setType(template.getType());
                        memberInfo.setSkipType(template.getSkipType());
                        memberInfoMapper.insert(memberInfo);
                        log.info("会员站内信通知完成"+msg.getMobile());
                    }
                    if (StringUtils.equals(type, String.valueOf(3))) {
                        SerializeObject<MemberThirdFindBean> serializeObject = memberThirdService.find(null, msg.getMemberId(), ThirdSourceEnum.PUSH.getType());
                        if (serializeObject.getData() != null) {
                            pushMsg(template.getTitle(), content, serializeObject.getData().getOpenId(), template.getSkipType(), msg.getMemberId(), msg.getMobile());
                        }
                    }
                }
            }
        } else {
            if(CommonConstants.YES == template.getIsSms()){
                sendSms(template.getFilingNumber(), msg.getMobile(), content, msg.getParamMap());
            }
            //发送站内信
            if(CommonConstants.YES == template.getIsInterLetter()){
                MemberInfo memberInfo = new MemberInfo();
                memberInfo.setId(UF.getRandomUUID());
                memberInfo.setMemberId(msg.getMemberId());
                memberInfo.setTitle(template.getTitle());
                memberInfo.setContent(content);
                memberInfo.setType(template.getType());
                memberInfo.setSkipType(template.getSkipType());
                memberInfoMapper.insert(memberInfo);
                log.info("会员站内信通知完成"+msg.getMobile());

                //个推
                SerializeObject<MemberThirdFindBean> serializeObject = memberThirdService.find(null, msg.getMemberId(), ThirdSourceEnum.PUSH.getType());
                int templateType = template.getType().intValue();
                boolean flag = true;
                //充值  银行卡支付 先无感充值到我们账户 之后再扣款
                if (templateType== CommonConstants.MsgType.RECHARGE.getIndex()){
                    log.info("消息请求："+msg.getParamMap().toString());
                    if ("NO".equalsIgnoreCase(msg.getParamMap().get("whetherPush")))
                        flag = false;
                }
                //绑定银行卡提醒  类型：5  待支付订单 类型：10
                if (serializeObject.getData() != null &&
                        templateType!= CommonConstants.MsgType.BIND_BANK_CARD.getIndex()    &&  //绑卡银行卡
                        templateType!= CommonConstants.MsgType.WAIT_PAY_ORDER.getIndex()    &&  //待支付订单
                        templateType!= CommonConstants.MsgType.SELL_GOLD.getIndex()         &&  //卖出黄金
                        templateType!= CommonConstants.MsgType.BUY_CURRENT_GOLD.getIndex()  &&  //购买活期金
                        templateType!= CommonConstants.MsgType.BUY_GOLD.getIndex()          &&  //购买定期金/活动金
                        templateType!= CommonConstants.MsgType.MALL_PAY_SUCCESS.getIndex()  &&  //商城支付成功
                        templateType!= CommonConstants.MsgType.BANK_MAINTENANCE.getIndex()  &&  //银行卡维护中
                        flag                                                                &&
                        templateType!= CommonConstants.MsgType.INVITE_FIRST_INVEST_AWARD.getIndex()//邀请首投奖励
                        ) {
                    //  暂时
                    if (templateType != CommonConstants.MsgType.PAY_EXPERIENCE.getIndex()
                            && templateType != CommonConstants.MsgType.EXTRACTGOLD_FINISH.getIndex()
                            && templateType != CommonConstants.MsgType.LEASEBACK_WITHOUT_COUPON.getIndex()
                            && templateType != CommonConstants.MsgType.ACCOUNT_PAY_CHANGE.getIndex()
                            && templateType != CommonConstants.MsgType.SELL_GOLD.getIndex()
                            && templateType != CommonConstants.MsgType.COUPON_NOTIFY.getIndex()) {

                        pushMsg(template.getTitle(), content, serializeObject.getData().getOpenId(), template.getSkipType(), msg.getMemberId(), msg.getMobile());
                    }
                }
            }
        }
    }

    public void sendSms(String filingNumber, String mobile, String content, Map<String, String> paramMap) {
        SmsBean smsBean = new SmsBean();
        smsBean.setType(String.valueOf(filingNumber));
        smsBean.setPhone(mobile);
        smsBean.setParamMap(paramMap);
        int res = smsService.send(smsBean);
        log.info("阿里短信发送结果：" + res);
        if(res != 0) {
            log.error("阿里短信发送失败");
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("appKey", appKey));
            nvps.add(new BasicNameValuePair("appSecret", appSecret));
            nvps.add(new BasicNameValuePair("phones", mobile));
            nvps.add(new BasicNameValuePair("content", SMS_SIGN_NAME+content));
            String data = HttpClientUtil.invokeHttp(url, nvps);
            log.info("专信云短信发送结果：" + data);
        }
    }

    public void pushMsg(String title, String content, String openId, int type, String memberId, String mobile) {
        Map<String,String> pushMap = new HashMap();
        pushMap.put("title", title);
        pushMap.put("content", content);
        pushMap.put("skipUrl",skipType.equalsIgnoreCase("h5")?h5Url:"");
        pushMap.put("skipType",skipType.equalsIgnoreCase("h5")?h5Url:String.valueOf(type));
        AppPushUtils appPushUtils =  new AppPushUtils(APPID_ANDROID,APPKEY_ANDROID,MASTERSECRET_ANDROID);
        IPushResult iPushResult = appPushUtils.pushTransmissionMsgToSingle(openId, null, pushMap);
        log.info("个推响应结果：" + iPushResult.getResponse().toString()+"----个推手机号："+mobile+"---个推会员号："+memberId);
    }
    /**
     * 站内信内容
     * @param paramMap
     * @param str
     * @return
     */
    public String getContent(Map<String,String> paramMap, String str){
        if(paramMap == null || paramMap.isEmpty()) return str;
        String content = str;
        if(!paramMap.isEmpty()){
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                str = str.replaceAll("#"+entry.getKey()+"#",entry.getValue());
            }
            return str;
        }
        return null;
    }
}
